package com.qiall.common.exception;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class BusinessResult<T> implements Serializable {

    private static final long serialVersionUID = -6389008129039777017L;

    private T body;

    /**
     * 异常状态码
     */
    private Integer status;

    /**
     * 用户看得见的异常，例如 用户名重复！！,
     */
    private String message;

    /**
     * 异常的名字
     */
    private String exception;

    /**
     * 对异常提示语进行封装
     */
    public static BusinessResult fail(ResultCode resultCode, Throwable e, String message) {
        BusinessResult result = BusinessResult.fail(resultCode, e);
        result.setMessage(message);
        return result;
    }

    /**
     * 对异常枚举进行封装
     */
    public static BusinessResult fail(ResultCode resultCode, Throwable e) {
        BusinessResult result = new BusinessResult();
        result.setMessage(resultCode.getErrorMessage());
        result.setStatus(resultCode.code());
        result.setException(e.getClass().getName());
        return result;
    }

    public static <T> BusinessResult success(T obj) {
        BusinessResult result = new BusinessResult();
        result.setMessage(ResultCode.SUCCESS.getErrorMessage());
        result.setStatus(ResultCode.SUCCESS.code());
        result.setBody(obj);
        return result;
    }
}
